<!--  -->
<template>
  <div>
    <van-form @submit="changeFromData" id="showpop">
      <div class="font15 mt10 pl10">
        <span class="titletext ">{{ titledata.title }}</span>
        <div class="graytext  mt10 font13">
          <span>工单编号：</span>
          <span class="titletext">{{ titledata.pmInsId }}</span>
        </div>
      </div>
      <div class="font11 mt10 bggray ptandpb10">
        <div class=" graytext pl10"><span>申请人：</span> <span class="titletext">{{ formdata.applicant }}</span></div>
        <div class=" graytext pl10"><span>地市：</span><span class="titletext">{{ formdata.city }}</span></div>
        <div class=" graytext pl10"><span>县区：</span> <span class="titletext">{{ formdata.area }}</span></div>
        <div class=" graytext pl10"><span>申请时间：</span> <span class="titletext">{{ formdata.applyTime }}</span></div>
      </div>
      <van-field readonly required name="caNumber" :value="formdata.caNumber" label="证书编号：" label-width="5em" />
      <van-field readonly required name="certificateOwner" :value="formdata.certificateOwner" label="证书主体："
        label-width="5em" />
      <van-field readonly required name="tradingCenter" :value="formdata.tradingCenter" label="交易中心："
        label-width="5em" />
      <van-field :readonly="!canEdit" required name="phoneNumber" v-model="formdata.phoneNumber" label="借用人联系方式："
                 maxlength="11" type="digit" label-width="8em" :right-icon="canEdit?'arrow':''"/>
      <div class="mt10" style=" display: flex;border-bottom: 1px solid #ebedf0;padding-right:5px;">
        <div class="blue_item"></div>
        <span class="font15" style="display: flex; line-height: 33px;margin-left:5px;  flex:1;">CA证书</span>
        <van-button block type="info" style="display: inline-block;width:auto;height: 33px;" native-type="button"
          v-if="canEdit" @click="selectCaFromList">新增
        </van-button>
      </div>
      <van-field readonly required name="reasons" :value="formdata.reasons" label="事由：" label-width="3em"/>
      <van-field readonly required name="TrueReturnTime" :value="formdata.TrueReturnTime" label="实际归还时间：" :rules="[{ required: canEdit, message: '请选择' }]"
                 label-width="7em" @click="canEdit ? showDateDialog = true : '' " :right-icon="canEdit?'arrow':''"/>
      <div class="mt10" style=" display: flex;border-bottom: 1px solid #ebedf0;">
        <div class="blue_item" />
        <span class="font15" style="display: flex; line-height: 33px;margin-left:5px;  flex:1;">备注内容</span>
      </div>
      <van-field :readonly="!canEdit" autosize type="textarea" rows="3" name="remark" v-model="formdata.remark"
        label="备注：" label-width="3em" maxlength="400" :right-icon="canEdit ? 'arrow' : ''" placeholder="最多 400 个字" />
      <div style="padding-bottom: 42px" v-if="canEdit && !showSuggest" />
      <div class="left_botton">
        <button block type="button" @click="tomsg()" style="color:#60a9ec; display: inline-block;width:100%;border: 0px solid #60a9ec;border-radius: 15px 0px 0px 15px;
          padding:10px 10px 10px 15px;font-size:13px">意见
        </button>
      </div>
      <div v-if="todotype || toread" class="footer">
        <van-button block type="info" native-type="submit"
          style="display: inline-block;width:100%;border: 0px solid #60a9ec;">流转下一步
        </van-button>
      </div>
    </van-form>
    <div v-if="showHistory" class="spline"></div>
    <van-field readonly center v-if="showHistory" label="当前办理人:" label-width="5.5em" />
    <div v-if="showHistory" class="font13 ptandpb10 pl16">
      <div>
        <span class="titletext font13">{{ historydata.MANAGER }}</span>
      </div>
      <div class="mt5">
        <span class="graytext font12 ">{{ historydata.DEPARTMENT }}</span>
      </div>
    </div>
    <div class="spline" v-if="showSuggest"></div>
    <div style="padding-bottom: 42px" v-if="showSuggest">
      <div class="stitle font14" id='target'>审批意见</div>
      <div v-if="approveList.length > 0" class="swrap" style="width: 100%">
        <div class="spiece_flex" v-for="(item, index) in approveList" :key="index">
          <div class="vertical-a-t display-ib" style="width: 25px">
            <i v-if="index == 0" class="iconfont icon-current font16 color-red2"></i>
            <i v-if="index > 0" class="iconfont icon-yiban font16 color-theme"></i>
            <div v-if="index != (approveList.length - 1)" class="optionline"></div>
          </div>
          <div class="vertical-a-t display-ib" style="width: calc(100%)">
            <div style="white-space: nowrap">
              <span class="color-theme font14">{{ item.producerName || '暂无' }}：</span>
              <span class="color-2 font14">{{ item.content || '暂无' }}</span>
            </div>
            <div class="mt05 color-8" style="display: flex; align-items: baseline">
              <div class="display-ib vertical-a-t font12" style="margin-top: 2px;width: 100%">
                {{ item.companyName + '-' + item.departmentName || '暂无' }}
              </div>
              <div class="display-ib vertical-a-t font12 text-r"
                style="margin-left: 10px; margin-top: 2px;text-align: right;width: 100%">
                {{ item.modifiedTime || '暂无' }}
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-else>
        <div class="color-9 font12 text-c">暂无数据</div>
      </div>
    </div>
    <van-popup v-model="showDateDialog" position="bottom" get-container="#showpop">
      <van-datetime-picker :formatter="formatter" type="date" @cancel="showDateDialog = false"
        @confirm="showDateDialogComfirm" :value="currentDate" />
    </van-popup>
    <selectListPage v-if="showSelectPage" v-on:update-flag="showSelectPage = false" v-on:select-item="handleSelectItem"
      :pageTitle="selectPageTitle" :url="selectUrl" :bodyParam="selectBodyParam" :queryParam="selectQueryParam"
      :listShow="selectListShow">
    </selectListPage>
  </div>
</template>

<script>
import {
  getFormDetail, getCertificateFormReturnByPmInsId,
  getWfOptMags, getWfLinkTracks
} from '@/api/dictapi'
import { mapGetters } from 'vuex'
import { Notify, Toast } from 'vant'
import moment from 'moment'
import util from '@/assets/js/public';
import selectListPage from '@/views/common/page_normal_select_list';
export default {
  data() {
    return {
      titledata: {},
      formdata: {},
      params: this.$route.query,
      todotype: false,
      approveList: [],
      showSuggest: true,
      historydata: {},
      toread: false,
      canEdit: false,
      showDateDialog: false,
      showSelectPage: false,
      showHistory: false,
      currentDate: new Date(),
      //选择页面参数
      selectPageType: 0,
      selectUrl: "",
      selectBodyParam: {},
      selectQueryParam: {},
      selectListShow: [],
      selectPageTitle: ""
    }
  },
  components: {
    selectListPage
  },
  computed: {
    ...mapGetters(['user']),
    ...mapGetters(['userinfo'])
  },
  //生命周期--创建完成
  created() {
    if (this.params.todoType == '1') {
      this.todotype = true;
      this.canEdit = this.params.location == 'dict.start'
      this.showSuggest = this.params.isdraw != '1';
      if (this.canEdit && !this.showSuggest) {
        return//起草不再请求数据
      }
    } else if (this.params.todoType == '2') {
      this.showHistory = true;
    } else if (this.params.todoType == '3') {
      this.toread = true;
    }
    this.getdetail();
  },
  //方法调用
  methods: {
    formatter(type, val) {
      if (type === 'year') {
        return `${val}年`;
      } else if (type === 'month') {
        return `${val}月`;
      } else if (type === 'day') {
        return `${val}日`;
      } else if (type === 'hour') {
        return `${val}时`;
      } else if (type === 'minute') {
        return `${val}分`;
      }
      return val;
    },
    showDateDialogComfirm(value) {
      this.currentDate = value
      this.showDateDialog = false;
      let time = moment(value).format('YYYY-MM-DD')
      this.formdata.TrueReturnTime = time
    },
    handleSelectItem(selectMap) {
      this.showSelectPage = false;
      if (selectMap.spare1 != '借出') {
        Notify("必须选择已借出证书")
        return;
      }
      this.formdata = selectMap
      this.$forceUpdate();
    },
    selectCaFromList() {
      this.selectPageTitle = "选择CA证书";
      this.selectUrl = "certificateForm$api$findAllByCondition";
      this.selectBodyParam = {};
      this.selectQueryParam = { "direction": "desc", "properties": "modifiedTime" };
      this.selectListShow = [
        { "key": "caNumber", "prefix": "证书编号" },
        { "key": "certificateOwner", "prefix": "证书主体" },
        { "key": "tradingCenter", "prefix": "交易中心" },
        { "key": "spare1", "prefix": "证书状态" }
      ];
      this.showSelectPage = true
    },
    tomsg() {
      document.getElementById('target').scrollIntoView({ behavior: 'smooth' })
    },
    getdetail() {
      Toast.loading({
        message: '加载中',
        forbidClick: false
      });
      getFormDetail(Object.assign(this.params, { userName: this.user.userName }))
        .then((result) => {
          this.fromdetal = {};
          Toast.clear();
          if (!result.data) {
            Notify(result.message);
            return;
          }
          if (result.data.data) {
            this.titledata = result.data.data;
          }
          this.getCertificateFormReturnByPmInsId();
        })
    },
    getCertificateFormReturnByPmInsId() {
      getCertificateFormReturnByPmInsId(Object.assign(this.params, { userName: this.user.userName }))
        .then((result) => {
          this.fromdetal = {};
          Toast.clear();
          if (!result.data) {
            Notify(result.message);
            return;
          }
          if (result.data.data) {
            this.formdata = result.data.data;
          }
          this.getWfOptMags();
        })
    },
    getWfOptMags() {
      getWfOptMags(Object.assign(this.params), { userName: this.user.userName })
        .then((result) => {
          Toast.clear();
          if (!result.data) {
            Notify(result.message);
            return;
          }
          this.approveList = result.data.data.reverse();
          if (this.showHistory == true) {
            this.getWfLinkTracks()
          }
        })
    },
    getWfLinkTracks() {
      getWfLinkTracks(Object.assign(this.params), { userName: this.user.userName })
        .then((result) => {
          Toast.clear();
          if (!result.data) {
            Notify(result.message);
            return;
          }
          if (result.data.data) {
            //数据过滤，并生成新的数组
            this.historydata = result.data.data.filter(item => item.CURRENTSTATE == 10)[0]
            if (this.historydata) {
              if (this.historydata.MANAGER) {
                this.showHistory = true;
              } else {
                this.showHistory = false;
              }
            } else {
              this.showHistory = false;
            }
          } else {
            this.showHistory = false;
          }
        })
    },

    // 流转下一步
    onNext() {

      var formSendData = { 'htmlParamMap': {} };
      formSendData.htmlParamMap = this.formdata;
      formSendData.id = this.titledata.id;
      formSendData.pmInsId = this.titledata.pmInsId;
      formSendData.processType = this.params.pmInsType
      formSendData.workItemId = this.params.workItemId;
      console.log('传给递交页面:', this.params)
      var params1 = {
        kv: {
          currentUserCode: util.encrypt(this.user.userName),
          source: 'MOBILE',
          location: this.params.location,
          processInstId: this.params.processInstId,
          processDefName: this.params.processDefName,
          processType: this.params.pmInsType,
        },
      };
      var params2 = {
        kv: {
          'currentUserCode': util.encrypt(this.user.userName),
          'source': 'MOBILE',
          'location': this.params.location,
          'processInstId': this.params.processInstId,
          'processType': this.params.pmInsType,
          'receiptCode': this.params.processInstId
        },
      };
      var params3 = {
        kv: {
          'source': 'MOBILE',
          'currentUserCode': util.encrypt(this.user.userName),
          'workItemId': this.params.todoType == 3 ? '' : this.params.workItemId,
          'processInstId': this.params.processInstId,
          'location': this.params.location,
          'notificationId': this.params.todoType == 3 ? this.params.wfnid : ''
        },
      };
      localStorage.setItem('submitPageParam', JSON.stringify({
        getDecisionsUrl: 'decisionAndUser$api$getDecisions',
        getDecisionsParams: params1,
        getUserUrl: 'decisionAndUser$api$getOrgAndUser',
        getUserParams: params2,
        tosubmintUrl: 'applicationFormEnhance$api$startSubmitProcess',
        tosubmintParams: params3,
        formData: formSendData,
        fromMoa: this.params.fromMoa,
        type: this.params.todoType == 3 ? 'toRead' : 'toDo'
      }));
      this.$router.push(
        {
          name: 'srqrsubmit'
        }
      );
    },

    changeFromData() {

      //提交流转
      if (this.canEdit) {
        const phonePass = this.newUtils.isPhoneNumber(this.formdata.phoneNumber)
        if (!phonePass) {
          Notify("请输入正确的借用人联系方式");
          return
        }

        if (!this.formdata.caNumber) {
          Notify("请选择CA证书");
          return
        }
      }


      this.controlRule(this.params, this.fromdata.projectID, function () {
        this.onNext();
      }.bind(this));

    },
  }
}
</script>
<style scoped>
/* @import url();*/
</style>